<?php

// Simple Captcha Generator

	if (!isset($_SESSION)) {
	  session_start();
	}

function generate_captcha($len){
	$word="";
	for($i=0;$i<$len;$i++){
		do{
			$c = chr(rand(ord("a"),ord("z") ));
		}while(!ctype_alnum($c));
		$word .= $c;
	}
	return $word;
}

function check_captcha($captcha){
	$check = false;
	$captcha = $_SESSION["captcha"];
	$test = $_REQUEST["key"];
	if($captcha==$test)
		$check=true;	
	return $check;
}

if(isset($_REQUEST['image'])){
	header("Content-type: image/png");
	$key = $_REQUEST['image'];
	$_SESSION["captcha"]=$key;
	$width = 200;
	$height = 70;
	$font = "./resources/FreeSerif.ttf";
	$im = imagecreatetruecolor($width, $height);
	$white = imagecolorallocate($im, 255, 255, 255);
	$black = imagecolorallocate($im, 0, 0, 0);
	$gray = imagecolorallocate($im, 100, 100, 100);
	imagefilledrectangle($im, 0, 0, $width-1, $height-1, $white);
	imagerectangle($im, 1, 1, $width-1, $height-1, $black);
    // dots
	for($i=0;$i<100;$i++){
		$d = rand(1, 5);
		imagefilledellipse($im, rand($d, $width-$d), rand($d, $height-$d), $d, $d, $gray);
	}
	$x=20;
	$y=10;
	// text
	for($i=0;$i<strlen($key);$i++){
		$angle = rand(-60,60);
		$size = rand(13,36);
		imagettftext($im, $size, $angle, $x+3, 50-$y+3, $gray, $font, substr($key,$i,1));
		imagettftext($im, $size, $angle, $x, 50-$y, $black, $font, substr($key,$i,1));
		$x += $size;
		$y = rand(0, 20);
	}
	/*
	imagesetthickness($im, 2);
	$z = 18;
	for($i=0;$i<$height/$z;$i++){
		imageline($im, 2, $i*$z, $width-2, $i*$z-2, $white);
	}
	for($i=0;$i<$width/10;$i++){
		imageline($im, $i*$z, 2, $i*$z-2 , $height-2, $white);
	}
	*/
	imagepng($im);
	imagedestroy($im);
}

?>